package chatTest;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import com.google.common.base.Strings;

public class Server {

	private static List<MyChannel> all = new ArrayList<MyChannel>();

	private boolean isRunning = true;

	public static void main(String[] args) {
		new Server().start();

	}

	private void start() {
		try {
			ServerSocket server = new ServerSocket(8888);

			for (; isRunning;) {
				Socket client = server.accept();
				MyChannel channel = new MyChannel(client);
				all.add(channel);
				new Thread(channel).start();
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private static class MyChannel implements Runnable {

		private DataOutputStream dos;

		private DataInputStream dis;

		private boolean isRunning = true;

		public MyChannel(Socket client) {
			try {
				dos = new DataOutputStream(client.getOutputStream());
				dis = new DataInputStream(client.getInputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void run() {
			for (; this.isRunning;) {
				sendOthers();
			}
		}

		private void sendOthers() {
			String msg = receive();
			for (MyChannel other : all) {
				if (other == this) {
					continue;
				}
				other.send(msg);
			}
		}

		private String receive() {
			String msg = "";
			try {
				msg = dis.readUTF();
			} catch (IOException e) {

				this.isRunning = false;
				all.remove(this);
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return msg;
		}

		private void send(String msg) {
			if (Strings.isNullOrEmpty(msg)) {
				return;
			}
			try {
				dos.writeUTF(msg);
				dos.flush();
			} catch (IOException e) {
				this.isRunning = false;
				all.remove(this);
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}
